package com.oromwin.repos.server.request.file;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.logging.Log;

import com.oromwin.repos.server.request.Request;
import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposClientConfig;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.helper.FSHelper;
import com.oromwin.repos.common.helper.IOHelper;

public class CreateFileRequest implements Request {
    private transient Log log = Logger.getLog(CreateFileRequest.class);
    private String VolumeId = null;
    private File FilePath = null;

    public CreateFileRequest(String volumeId, File filePath) {
        VolumeId = volumeId;
        FilePath = filePath;
    }

    public void send(DataOutputStream dos) throws ReposException {
        if (!FSHelper.ls(FilePath)) {
            String message = "File not found " + FilePath.toString();
            throw ReposException.create(log, message);
        }
        try {
            IOHelper.writeUTF8(dos, this.getClass().getName());
            IOHelper.writeUTF8(dos, VolumeId);
            IOHelper.writeUTF8(dos, FilePath.getName());
            long fileLength = FilePath.length();
            dos.writeLong(fileLength);
            int off = 0;
            int len = ReposClientConfig.getDefaultBufferSize(); // ReposClientConfig.getInstance().getReposSocketIOBuffSize();
            int read = 0;
            byte[] b = new byte[len];
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(FilePath));
            while ((read = bis.read(b, off, len)) > 0) {
                dos.write(b, off, read);
            }
            dos.flush();
        } catch (NullPointerException e) {
            throw ReposException.create(log, e, "Can't find file, path {"+FilePath+"}");
        } catch (IOException e) {
            throw ReposException.create(log, e, "Failed to write into output stream, {"+e.getMessage()+"}");
        }
    }
}
